package com.samp.util;

import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class MapUtils {
    /**
     * 按value排序，需要定义一个按value比较的比较器，然后用LinkHashMap来保存比较结果。
     * @param oriMap
     * @return
     */
    public static Map<String,Integer> sortedByValue(Map<String,Integer> oriMap){
        if( oriMap == null || oriMap.size() == 0 ){
            return  null;
        }
        List<Map.Entry<String ,Integer>> entryList = new ArrayList<Map.Entry<String ,Integer>>(oriMap.entrySet());
        Collections.sort(entryList, new MapValueComparator());
        Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
        Map<String, Integer> resultMap = new LinkedHashMap<>();
        Map.Entry<String,Integer> entry ;
        while (iter.hasNext()){
            entry = iter.next();
            resultMap.put(entry.getKey(), entry.getValue());
        }
        return resultMap;
    }

    /**
     * 将Map<String, List<String>>转换成List,key打头，中间用指定分隔符分开。
     * @param mapData
     * @param separator
     * @return
     */
    public static List<String> mapToList(Map<String, List<String>> mapData, String separator){
        List<String> resutList = new ArrayList<>();
        Iterator iterator = mapData.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String)entry.getKey();
            List<String> value = (List<String>)entry.getValue();
            if( value != null && value.size() > 0 ) {
                resutList.add(key + separator + StringUtils.join(value, separator));
            }
        }
        return resutList;
    }


}

class MapValueComparator implements Comparator<Map.Entry<String, Integer>> {

    @Override
    public int compare(Map.Entry<String, Integer> me1, Map.Entry<String, Integer> me2) {
        if( me1.getValue().equals(me2.getValue() )){
//            return me1.getKey().compareTo(me2.getKey());
            return me2.getKey().compareTo(me1.getKey()); //降序排列
        }else {
//            return me1.getValue().compareTo(me2.getValue());
            return me2.getValue().compareTo(me1.getValue());
        }
    }
}